<script setup>
import CustomPopup from '@/components/custom-popup.vue';
import { computed, ref, watch } from 'vue';
import { useAreaStore } from '@/sheep/store/area';
import CustomCommonFixedBottom from '@/components/custom-common-fixed-bottom.vue';

const { getArea } = useAreaStore();

const props = defineProps({
  modelValue: Array,
  title: {
    type: String,
    default: '选择区域',
  },
});

const popupRef = ref(null);
const areaData = ref([]);
const currentIndex = ref([0, 0, 0]);
// 列是否还在滑动中，微信小程序如果在滑动中就点确定，结果可能不准确
const moving = ref(false);
const show = ref(false);
const emits = defineEmits(['confirm', 'cancel', 'change']);

const provinceList = computed(() => {
  if (!areaData.value) return [];
  return areaData.value;
});

const cityList = computed(() => {
  if (provinceList.value.length === 0) return [];
  const item = provinceList.value[currentIndex.value[0]];
  if (!item) return [];
  return item.children || [];
});
const districtList = computed(() => {
  if (cityList.value.length === 0) return [];
  const item = cityList.value[currentIndex.value[1]];
  return item.children || [];
});

watch(() => props.modelValue, () => {
  getCurrentIndexByValue();
}, {
  immediate: true,
  deep: true,
});

watch(() => areaData.value, () => {
  getCurrentIndexByValue();
});

function getCurrentIndexByValue() {
  if (props.modelValue) {
    if (props.modelValue[0]) {
      const index = provinceList.value.findIndex(item => item.name === props.modelValue[0]);
      currentIndex.value[0] = index === -1 ? 0 : index;
    }
    if (props.modelValue[1]) {
      const index = cityList.value.findIndex(item => item.name === props.modelValue[1]);
      currentIndex.value[1] = index === -1 ? 0 : index;
    }
    if (props.modelValue[2]) {
      const index = districtList.value.findIndex(item => item.name === props.modelValue[2]);
      currentIndex.value[2] = index === -1 ? 0 : index;
    }
  }
}

getArea().then((res) => {
  areaData.value = res;
});

// 标识滑动开始，只有微信小程序才有这样的事件
const pickstart = () => {
  // #ifdef MP-WEIXIN
  moving.value = true;
  // #endif
};

// 标识滑动结束
const pickend = () => {
  // #ifdef MP-WEIXIN
  moving.value = false;
  // #endif
};

const onCancel = () => {
  emits('cancel');
  show.value = false;
};

// 用户更改picker的列选项
const change = (e) => {
  if (
    currentIndex.value[0] === e.detail.value[0] &&
    currentIndex.value[1] === e.detail.value[1]
  ) {
    // 不更改省市区列表
    currentIndex.value[2] = e.detail.value[2];
    return;
  } else {
    // 更改省市区列表
    if (currentIndex.value[0] !== e.detail.value[0]) {
      e.detail.value[1] = 0;
    }
    e.detail.value[2] = 0;
    currentIndex.value = e.detail.value;
  }
  emits('change', currentIndex.value);
};

// 用户点击确定按钮
const onConfirm = (event = null) => {
  // #ifdef MP-WEIXIN
  if (moving.value) return;
  // #endif
  let index = currentIndex.value;
  let province = provinceList.value[index[0]];
  let city = cityList.value[index[1]];
  let district = districtList.value[index[2]];
  let result = {
    province_name: province.name,
    province_id: province.id,
    city_name: city.name,
    city_id: city.id,
    district_name: district.name,
    district_id: district.id,
  };

  if (event) emits(event, result);
};

const getSizeByNameLength = (name) => {
  let length = name.length;
  if (length <= 7) return '';
  if (length < 9) {
    return 'font-size:28rpx';
  } else {
    return 'font-size: 24rpx';
  }
};

function open() {
  popupRef.value.open();
  show.value = true;
}

function close() {
  popupRef.value.close();
  show.value = false;
}

defineExpose({
  open,
  close,
});
</script>

<template>
  <custom-popup
    ref="popupRef"
    :title="title"
    bg-color="#fff"
    @close="onCancel"
    height="auto"
    :scroll-view="false">
    <view class="region-container">
      <view class="picker-container">
        <picker-view
          v-if="provinceList.length && cityList.length && districtList.length"
          :value="currentIndex"
          @change="change"
          class="ui-picker-view"
          @pickstart="pickstart"
          @pickend="pickend"
          indicator-style="height: 68rpx"
        >
          <picker-view-column>
            <view class="ui-column-item" v-for="province in provinceList" :key="province.id">
              <view :style="getSizeByNameLength(province.name)">{{ province.name }}</view>
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="ui-column-item" v-for="city in cityList" :key="city.id">
              <view :style="getSizeByNameLength(city.name)">{{ city.name }}</view>
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="ui-column-item" v-for="district in districtList" :key="district.id">
              <view :style="getSizeByNameLength(district.name)">{{ district.name }}</view>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    <template #bottom>
      <custom-common-fixed-bottom :fixed="false" :safe-height="false">
        <u-button type="primary" @click="onConfirm('confirm')">确认</u-button>
      </custom-common-fixed-bottom>
    </template>
  </custom-popup>
</template>

<style scoped lang="scss">
.region-container {
  height: 500rpx;
  display: flex;
  flex-direction: column;

  .picker-container {
    flex: 1;
  }

  .ui-picker-view {
    height: 100%;
    box-sizing: border-box;
  }

  .ui-column-item {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #333;
    padding: 0 8rpx;
  }
}
</style>

